package twitter.Server;



import twitter.TwitterLibrary.SocketConfig;
import twitter.TwitterLibrary.Utility;

import org.apache.log4j.*;

import Muilticast.MulticastNoticeSender;
import Twitter.RequestSender.PrimaryFailureListenerSender;
import Twitter.RequestSender.ServerRegistrationSender;




/************************************************
 * this class is designed for back end server
 * @author fang
 *
 */
public class BackendServer extends Server{
	static Logger logger = Logger.getLogger(BackendServer.class);

	private boolean isPrimary;
/************************************************
 * Class construcot
 */
	public BackendServer(boolean isPrimary) {
		super();

		this.isPrimary=isPrimary;
		System.out.println("isPrimary:"+isPrimary);
		if(isPrimary)
		{
			SocketConfig.serverType=ServerType.PrimaryServer;
		}
		else
		{
			SocketConfig.serverType=ServerType.BackendServer;
		}

	}
/***********************************************
 * for run the server and test
 * @param args
 */
	public static void main(String args[]) {
		Server server=null;
		if(args.length<1)
		{
			System.out.println("please Input my IP address");
			 return;
		}
		else if(args.length==1)
		{
			SocketConfig.myIp=args[0];
			server=new BackendServer(false);
			server.startServer("end",SocketConfig.backendPort);
		}
		
		else
		{
		System.out.println("args[0]"+args[0]);
		SocketConfig.myIp=args[0];
			if(args[1].equals("true"))
			{
				server=new BackendServer(true);
			}
			else
			{
				server=new BackendServer(false);
			}
			//boolean isPrimary=Boolean.getBoolean(args[0]);
			//SocketConfig.myIp="localhost";
			
			//System.out.println("isPrimary "+isPrimary);
			//server=new BackendServer(isPrimary);
				
			
			server.startServer("end",SocketConfig.backendPort);
		}
		
		
	}
/***************************************
 * start the server
 */
	public void startServer(String end,int port) {
		utility.setLogger(logger, "backend.log");	
		
		
		if(SocketConfig.serverType==ServerType.PrimaryServer)
		{
			//MulticastNoticeSender multicastNotice=new MulticastNoticeSender();
			System.out.println("99999");
			ServerRegistrationSender registration=new ServerRegistrationSender(this.utility);
			utility.threadPool.execute(registration);
			
		}
		else
		{
			PrimaryFailureListenerSender failureListener=new PrimaryFailureListenerSender(utility);
			utility.threadPool.execute(failureListener);
		}
		
		super.startServer(end, port);
		
	}
}
